#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>

pthread_mutex_t lock;

void* func(void*);

int main(int argc,char** argv)
{
  pthread_mutex_init(&lock,NULL);
  int* data;
  pthread_t tid;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
  data = malloc(sizeof(int));
  
  int ret;
  for(int i = 0;i < 15;i++) 
  {
      ret = pthread_mutex_trylock(&lock);
      if(ret == 0)
      {

        *data = i;
        pthread_create(&tid,&attr,func,data);
        pthread_mutex_unlock(&lock);
      }
  }

  pthread_attr_destroy(&attr);
  pthread_mutex_destroy(&lock);
  pthread_exit((void*)0);
}

void* func(void* data)
{
  int ret;
  while(1)
  {
    ret = pthread_mutex_trylock(&lock);
    if(ret == 0)
    {
      printf("I am %d pthread\n",*(int*)data);
      pthread_mutex_unlock(&lock);
      sleep(1);
    }
  }
  return NULL;
}
